/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: TextClientContinuous.cpp
 *
 * \file
 * \brief This is a program that takes text input until there is
 *        long enough pause. Then it sents the string. This client
 *        can be used for example to send data from Nuance's speech
 *        recognition software (Dragon NaturallySpeaking).
 * \author Seppo Heikkila <seppo.heikkila@tkk.fi>
 *         Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include "TextClient.hpp"
#include <curses.h>
#include <math.h>
//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
// Objects
static bool run = true;
static gimi::GIMI g;
static MaCI::Text::CTextClient textC(&g, 0);


//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
static int verbose = 1;
//*****************************************************************************
//*****************************************************************************
static void DoText()
{
  // Timing shit
  struct timespec start, stop;
  clock_gettime(CLOCK_REALTIME,&start);
  clock_gettime(CLOCK_REALTIME,&stop);
  double duration= (stop.tv_sec - start.tv_sec) + (double)(stop.tv_nsec - start.tv_nsec) / 1000000000.0;
  printf("time elapsed = %.9f s", duration);

  // Initialize Curses (After this point, don't use printf family calls!)
  initscr(); 
  cbreak(); 
  nonl();
  intrflush(stdscr, FALSE);
  keypad(stdscr, TRUE);
  scrollok(stdscr, TRUE);

  nodelay(stdscr, TRUE);

  // After this point, we don't want dPrint to print to Screen, so we disable it.
  debugSetPrintLevel(0);
  debugSetLogLevel(10);
  clear();
  printw("Welcome to Text client test program.\n\n");

  std::string msg = "";
  double max_allowed_delay = 0.25;
  double since_last = 0;
  char value;
  clock_gettime(CLOCK_REALTIME,&start);
  do {
    value = getch();
    clear(); // After input, clear the screen. Not after processing!
    clock_gettime(CLOCK_REALTIME,&stop);
    since_last = (stop.tv_sec - start.tv_sec) + (double)(stop.tv_nsec - start.tv_nsec) / 1000000000.0;
    if(value != ERR) {
      printw("Got char\n");
      msg += (char)value;
      clock_gettime(CLOCK_REALTIME,&start);
    }else {
      printw("Please input chars (current count = %d)\n", msg.size());
      usleep(10*1000);
    }
    if(since_last > max_allowed_delay ) {
      if(msg.size() > 2) {
	printw("Message sent: %s\n", msg.c_str());
	textC.SendText(msg);
	msg = "";
	clock_gettime(CLOCK_REALTIME,&start);
      }
    }
    if(since_last > max_allowed_delay*5 ) {
      msg = "";
      clock_gettime(CLOCK_REALTIME,&start);
    }
  } while(run);
  
  // Close curses.
  endwin();
  
      
}
//*****************************************************************************
void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tJointGroupCtrlClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tUse 'name' as Text target\n");
  fprintf(stderr,"  \t\t\t\tOR\n"); 
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

int main(int argc, char *argv[]) {
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";
  std::string datasourceMaCISL;
  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(8);
  debugSetLogFilename("TextClientExample.log");
  debugSetLogLevel(10);
  // Greet
  fprintf(stderr,
	  "\nTextClientExample - MaCI Text Interface Example - v0.0\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "s:S:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 's':
      gimnetSourceName = optarg;
      dPrint(3,"Using GIMnet source name '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }


  MaCI::EMaCIError e;
  
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());



    // Assign default target.
    if (gimnetSourceName.size()) {
      textC.SetDefaultTarget(gimnetSourceName);
      
    } else {
      // GIMI is Open(), so we can execute this.
      MaCI::MaCICtrl::SMaCISL sl(datasourceMaCISL);
      if (sl.IsValidFQMaCISL()) {
        textC.SetDefaultTarget(sl, 10000);
      }
    
    }
    // Attempt to Open Client
    if ( (e = textC.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open TextClient instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {

      DoText();
      textC.Close();
    }
  }
  
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
